import React from 'react';
import ReactDOM from 'react-dom';
import { inject, observer } from 'mobx-react';
import { autorun, toJS } from 'mobx'
import { withRouter, HashRouter as Router, Route, Switch } from 'react-router-dom';
import { Tools, SearchBar, Icon, PullToRefresh, Popover, Button } from 'weaver-mobile';
import { Browser } from 'weaver-mobile-page';
import QueueAnim from 'rc-queue-anim';
import MenuList from '../../../public/menulist'
import ScrollSelect from '../../../public/scrollselect'
import FoldList from '../../../public/foldlist'
import LevelList from '../../../public/levellist'
import WrMenu from '../../../public/menu'
import WrAlertPage from '../../../public/alertPage'
import TaskMainAdvancedSearch from '../taskMainAdvancedSearch/taskMainAdvancedSearch'
import Tagmanage from '../../../public/tagmanage'
import WrOrg from '../../../public/org'
import Wrttag from '../../../public/wrttag'
import * as TaskMainApis from '../../../api/task/taskMain'

const getLabel = Tools.getLabel

@inject('taskMainStore', "taskCommonStore")
@withRouter
@observer
class TaskMain extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      advancedParams: {},
      down: true,
      refreshing: false,
      isLoading: false,
      needSticky: true,
      moduleRight: "",
      taskMainTagBrowserStore: new Browser.Store({ route: '/taskHome/taskMain/' })
    }
  }

  componentWillMount() {
    this.setState({
      isLoading: true
    })

    TaskMainApis.checkHasRigth({
      id: 2
    }).then(res => {
      if (res.status && res.isRight) {
        this.setState({
          moduleRight: "1"
        })
        this.doNext()
      } else {
        this.setState({
          moduleRight: "0"
        })
      }
    })
  }

  componentDidUpdate() {
    let rf = ReactDOM.findDOMNode(this.ptr)
    if (rf) {
      let aptrw = rf.children[0].children[0]
      let aptr = aptrw.parentNode
      aptr.removeChild(aptrw)
      aptr.appendChild(aptrw)
    }
  }

  componentWillReceiveProps(nextProps) {
    const { condtype, changeCondtype, advancedParams, changeAdvancedParams } = this.props.taskMainStore
    // console.log(condtype + "--" + nextProps.match.params.condtype)
    if (condtype && nextProps.match.params.condtype != condtype) {
      if (/^\d+$/.test(nextProps.match.params.condtype)) {
        changeCondtype(nextProps.match.params.condtype)
        if (nextProps.match.params.condtype != "0" || nextProps.match.params.condtype != "9") {
          changeAdvancedParams({ ...advancedParams, subordinate: [] })
        } else {
          this.doAdvancedSearch()
        }
      }
    }
  }

  componentDidMount() {

  }

  componentWillUnmount() {
    const { disposer1, disposer2 } = this.state
    disposer1 && disposer1()
    disposer2 && disposer2()
    this.props.taskMainStore.jumpTaskFbMonitor = null
  }

  doNext = () => {
    const { condtype, changeCondtype, defaultCondtype, changeViewId, changeSelectViewType, changeSelectTaskStatus } = this.props.taskMainStore
    if (!condtype) {
      this.initViewInfo().then(data => {
        data.condtype && changeCondtype(data.condtype == defaultCondtype ? "1" : data.condtype)
        data.selectViewType && changeSelectViewType(data.selectViewType)
        data.selectTaskStatus && changeSelectTaskStatus(data.selectTaskStatus)
        data.viewId && changeViewId(data.viewId)
        this.props.history.replace("/taskHome")
      })
    } else {
      let disposer1 = autorun(() => {
        const { advancedParams } = this.props.taskMainStore

        if (this.state.advancedParams != advancedParams) {   // 需要执行高级搜索
          this.state.advancedParams = advancedParams
          this.doAdvancedSearch()
        }
      })

      let disposer2 = autorun(() => {
        const { jumpTaskFbMonitor } = this.props.taskMainStore
        if (this.state.jumpTaskFbMonitor != jumpTaskFbMonitor) {
          this.state.jumpTaskFbMonitor = jumpTaskFbMonitor
          if (jumpTaskFbMonitor.taskid) {
            this.props.history.push("/taskHome/taskDetail/" + jumpTaskFbMonitor.taskid + "?page=3")
          }
        }
      })

      this.state.disposer1 = disposer1
      this.state.disposer2 = disposer2

      this.initNewMap()
    }
  }

  initNewMap = () => {
    const { changeNewMap } = this.props.taskMainStore
    TaskMainApis.checkNewMap({}).then(res => {
      if (res.status) {
        changeNewMap(res.newMap)
      }
    })
  }

  initViewInfo = () => {
    const { condtype, defaultCondtype, changeCondtype } = this.props.taskMainStore
    return new Promise((rs, rj) => {
      TaskMainApis.taskViewOperation({
        operation: "search"
      }).then(res => {
        if (res.status) {
          if (res.viewId == 0) {
            rs({
              viewId: "0",
              condtype: defaultCondtype
            })
          } else {
            rs({
              viewId: res.viewId,
              condtype: res.condtype,
              selectViewType: res.sorttype,
              selectTaskStatus: res.cstatus
            })
          }
        } else {
          rs({
            condtype: defaultCondtype
          })
        }
      })
    })
  }

  onSearchBarBlur = () => {
    this.doAdvancedSearch()
  }

  doAdvancedSearch = () => {
    const { params } = this.state
    const { condtype, selectViewType, selectTaskStatus } = this.props.taskMainStore
    const { taskname, principal, urgentLevel, begindate, begindate1, enddate, enddate1, orderby, orderbytype, tagArray, subordinate } = this.props.taskMainStore.advancedParams

    this.refreshTaskList({
      ...params,
      taskname,
      condtype,
      selectViewType,
      selectTaskStatus,
      principalid: principal && principal.length > 0 ? principal[0].id : "",
      level: urgentLevel,
      begindate,
      begindate1,
      enddate,
      enddate1,
      orderby,
      orderbytype,
      tag: tagArray.map((d, i) => d.id).join(","),
      hrmid: subordinate.length > 0 ? subordinate[0].id : ""
    })
  }

  onAdvancedSearchBtnClick = () => {
    this.props.history.push("/taskHome/taskMain/advancedSearch")
  }

  onParamsFieldValueChange = (fieldName, fieldValue) => {
    const { clearAdvancedParams } = this.props.taskMainStore
    this.props.taskMainStore[fieldName] = fieldValue
    if (fieldName === "condtype") {
      // 清空高级搜索条件
      clearAdvancedParams()
    }
    this.doAdvancedSearch()
  }

  refreshTaskList = (params) => {
    const { taskMainStore, taskCommonStore } = this.props
    const { selectViewType, selectTaskStatus, condtype, taskname, principalid, begindate, begindate1, enddate, enddate1, level, orderby, orderbytype, tag, hrmid } = params

    taskCommonStore.showLoading()
    taskMainStore.changeShowBatchChoose(false)
    TaskMainApis.getTaskList({
      sorttype: selectViewType,
      orderby,
      orderbytype: orderbytype ? orderbytype : "desc",
      pagesize: selectViewType == "1" ? "10" : "5",
      condtype: condtype === "9" ? "0" : condtype,
      status: selectTaskStatus,
      taskname,
      begindate,
      begindate1,
      enddate,
      enddate1,
      principalid,
      level,
      lev: level,
      tag,
      hrmid
    }).then(res => {
      taskCommonStore.closeLoading()
      this.setState({
        refreshing: false,
        isLoading: false
      })
      if (res.api_status) {
        taskMainStore.setTaskBackendDatas(res.datas)
        res.datetype.forEach((d, i) => {
          d.isopen = true
        })
        taskMainStore.setTaskListDatetype(res.datetype)
        taskMainStore.changeHasmore(res.hasmore)
        taskMainStore.changeTotal(res.total)
        taskMainStore.changePagenum(1)
        taskMainStore.initTaskListDatas()
      }
    })
  }

  getTaskChildren = (itemtask) => {
    const { taskMainStore } = this.props
    const { selectViewType } = taskMainStore
    TaskMainApis.getChildTaskList({
      taskid: itemtask.id,
      sorttype: selectViewType
    }).then(res => {
      let children = []
      res.datas.forEach((d, i) => {
        children.push(taskMainStore.formatBackendData(d))
      })
      itemtask.children = children
      taskMainStore.changeTaskListDatas([...taskMainStore.taskListDatas])
    })
  }

  onCreateNewTask = (datetype) => {
    const { selectViewType } = this.props.taskMainStore
    this.props.history.push("/taskHome/newTask?sorttype=" + selectViewType + "&datetype=" + (datetype || ""))
  }

  onTaskItemClick = (taskid) => {
    this.props.history.push("/taskHome/taskDetail/" + taskid)
  }

  onOpenFoldIconClick = (currdata) => {
    const { childrenOpen = false, id } = currdata
    currdata.originalData.isopen = childrenOpen
  }

  onBottomMenuSelect = (data) => {
    const { changeCondtype, newMap, changeNewMap } = this.props.taskMainStore
    let condtype = data.key
    changeCondtype(condtype === "9" ? "0" : condtype)
    this.updateViewInfo()
    if (condtype !== "9") {
      this.onParamsFieldValueChange("condtype", condtype)
      changeNewMap({ ...newMap, [condtype]: 0 })
      this.props.history.push("/taskHome/taskMain/" + condtype)
    } else {
      this.onParamsFieldValueChange("condtype", "0")
      this.props.history.push("/taskHome/taskMain/subUser")
    }
  }

  updateViewInfo = () => {
    const { condtype, viewId, selectViewType, selectTaskStatus } = this.props.taskMainStore
    TaskMainApis.taskViewOperation({
      viewId,
      sorttype: selectViewType,
      condtype,
      status: selectTaskStatus
    })
  }

  handleSelectSubUser = (id, datas, type) => {
    const { condtype, advancedParams, changeAdvancedParams } = this.props.taskMainStore
    datas && changeAdvancedParams({ ...advancedParams, subordinate: datas })
    this.props.history.push("/taskHome/taskMain/" + condtype)
  }

  onTagBrowserChange = (data) => {
    const { taskCommonStore } = this.props
    const { batchSetTagOperation, taskListDatas } = this.props.taskMainStore
    let tagtype
    if (Array.isArray(data)) {   // 点击清除按钮
      tagtype = "3"
    } else {  // 点击确定按钮
      tagtype = "2"
    }

    let tagids = ""
    if (tagtype != "3") {
      tagids = toJS(data).map((d, i) => d.id).join(",")
    }

    batchSetTagOperation({
      tagids,
      tagtype,
      opentagtype: "1",   // 打开标签浏览按钮的方式为批量设置方式
      infos: getLabel(516448, "确定要清除选中数据的所有标签吗？")
    })
  }

  renderAdvancedSearch = () => {
    return <TaskMainAdvancedSearch />
  }

  renderSubUser = () => {
    const { orgTreeStore, condtype } = this.props.taskMainStore
    return (
      <QueueAnim>
        <div className="main-subuser-wrapper">
          <WrOrg
            orgStore={orgTreeStore}
            type={"sub"}
            onSelect={this.handleSelectSubUser}
          />
        </div>
      </QueueAnim>
    )
  }

  renderTagManage = () => {
    return (
      <Tagmanage />
    )
  }

  render() {
    const { advancedSearchPopoverVisible, showBatchChoose, changeShowBatchChoose, isBatchChoosed, changeIsBatchChoosed, batchChoose, batchChooseNum, clearBatchInfo,
      onTaskCheckedChange, changeAdvancedSearchPopoverVisible, bottomMenuDatas, viewTypeList, taskStatusOptions, taskListDatas,
      taskListDatetype, onTaskGetMore, onTaskGetMore1,
      hasmore, showGetMore, pagenum, total, advancedParams, condtype, selectTaskStatus, selectViewType } = this.props.taskMainStore
    let { moduleRight, isLoading, needSticky, taskMainTagBrowserStore } = this.state

    return (moduleRight !== "" && condtype != "" &&
      (moduleRight == "1" ?
        <div className="workrelate-mobile-taskmain">
          <div className="main-head-wrapper">
            <SearchBar
              className="search-select"
              value={advancedParams.taskname}
              placeholder={getLabel(500351, '请输入关键字')}
              showExtraButton
              extraButton={[
                {
                  key: 'advanced',
                  show: <Icon key="filter-o" type="filter-o" />
                },
                {
                  key: 'drop',
                  show: (
                    <Popover
                      mask
                      visible={advancedSearchPopoverVisible}
                      overlay={[
                        <Popover.Item key="1">{getLabel(30884, '标签设置')}</Popover.Item>,
                        <Popover.Item key="2">{getLabel(390705, '批量标记')}</Popover.Item>
                      ]}
                      align={{
                        overflow: { adjustY: 0, adjustX: 0 },
                        offset: [0, 0],
                      }}
                      onSelect={(data) => {
                        changeAdvancedSearchPopoverVisible(false)
                        let key = data.key
                        if (key === "1") {
                          this.props.history.push("/taskHome/taskMain/tagManage")
                        } else if (key === "2") {
                          changeShowBatchChoose(true)
                        }
                      }}
                      onVisibleChange={(advancedSearchPopoverVisible) => {
                        changeAdvancedSearchPopoverVisible(advancedSearchPopoverVisible)
                      }}
                    >
                      <Icon key="ellipsis" type="ellipsis" />
                    </Popover>
                  )
                }
              ]}
              onChange={(val) => {
                advancedParams.taskname = val
              }}
              onBlur={() => { this.onSearchBarBlur() }}
              onExtraButtonClick={(key) => {
                key === "advanced" && this.onAdvancedSearchBtnClick()
              }}
              onClear={(val) => { advancedParams.taskname = "" }}
            />

            {
              !showBatchChoose &&
              <div className="view-status-select-wrapper">
                <MenuList
                  data={viewTypeList}
                  selectKey={selectViewType}
                  onChange={(selectKey) => {
                    this.onParamsFieldValueChange("selectViewType", selectKey)
                    this.updateViewInfo()
                  }}
                  width={240}
                  itemWith={140}
                  showMenu={false}
                  showSelectText={true}
                />
                {
                  selectViewType != "5" &&
                  <ScrollSelect
                    width={80}
                    height={30}
                    title={getLabel(18214, '请选择')}
                    bgcolor={"#fff"}
                    data={taskStatusOptions}
                    value={selectTaskStatus}
                    onChange={(value) => {
                      this.onParamsFieldValueChange("selectTaskStatus", value)
                      this.updateViewInfo()
                    }}
                  />
                }
              </div>
            }

            {
              showBatchChoose &&
              <div className="batch-choose-wrapper">
                <span
                  onClick={() => {
                    clearBatchInfo()
                  }}
                >
                  {getLabel(31129, "取消")}
                </span>
                <span>
                  {getLabel(513668, "已选择{num}条数据").replace("{num}", batchChooseNum)}
                </span>
                <span
                  style={{ color: isBatchChoosed && "#55B1F9" }}
                  onClick={() => {
                    changeIsBatchChoosed(!isBatchChoosed)
                    batchChoose(!isBatchChoosed)
                  }}
                >
                  {getLabel(556, "全选")}
                </span>
              </div>
            }
          </div>

          <div className="main-content-wrapper workrelate-swipe" ref={mcw => { this.mcw = mcw }}>
            <div className="refresh-wrapper">
              <PullToRefresh
                ref={el => this.ptr = el}
                damping={70}
                distanceToRefresh={35}
                style={{
                  overflowY: 'auto'
                }}
                direction={this.state.down ? 'down' : 'up'}
                refreshing={this.state.refreshing}
                onRefresh={() => {
                  this.setState({
                    refreshing: true
                  }, () => {
                    this.doAdvancedSearch()
                  })
                }}
              >
                {
                  taskListDatetype.length == 0 ?
                    <LevelList
                      key={new Date().getTime() + selectViewType}
                      bgColor={"#fff"}
                      showseq={true}
                      data={taskListDatas}
                      hasMore={hasmore}
                      getMore={() => { onTaskGetMore1({ params: this.state.params, other: { total, pagenum } }) }}
                      showGetMore={showGetMore}
                      onItemClick={(dataid) => { this.onTaskItemClick(dataid) }}
                      getChildren={selectViewType == "4" ? (dataid) => { this.getTaskChildren(dataid) } : null}
                      onAddIconClick={() => { this.onCreateNewTask() }}
                      showCheckbox={showBatchChoose}
                      onCheckedChange={onTaskCheckedChange}
                    />
                    :
                    taskListDatetype.map((d, i) => {
                      return (
                        <FoldList
                          key={new Date().getTime() + d.id + ""}
                          sticky={needSticky}
                          headColor={d.color}
                          headIconclass={"serial-node"}
                          headIconsize={"lg"}
                          headIconStyle={{ width: 25 }}
                          count={d.total}
                          title={d.name}
                          showseq={true}
                          open={d.isopen}
                          data={taskListDatas.filter((dt, i) => { return dt.treetype == "m" + d.id })}
                          hasMore={d.hasmore}
                          getMore={() => { onTaskGetMore({ params: this.state.params, datetype: d }) }}
                          showGetMore={d.showGetMore}
                          onItemClick={(dataid) => { this.onTaskItemClick(dataid) }}
                          onAddIconClick={() => { this.onCreateNewTask(d.id) }}
                          showCheckbox={showBatchChoose}
                          onCheckedChange={onTaskCheckedChange}
                        />
                      )
                    })
                }
                {
                  (!isLoading && taskListDatetype.length == 0 && taskListDatas.length == 0) &&
                  <WrAlertPage show={true} msg={getLabel(83553, "暂无数据")} icon={"no-data"} top="40%" />
                }
              </PullToRefresh>
            </div>
          </div>


          <div className="main-foot-wrapper">
            {
              showBatchChoose ?
                <div className="batch-tag">
                  <Button
                    type="primary"
                    disabled={batchChooseNum == 0}
                    onClick={() => {
                      let taskMainTagBrowserStore = new Browser.Store({ route: '/taskHome/taskMain/' + condtype })
                      this.setState({
                        taskMainTagBrowserStore
                      }, () => {
                        this.props.history.push(taskMainTagBrowserStore.path)
                      }) 
                    }}
                  >
                    {getLabel(390705, '批量标记')}
                  </Button>
                  <div style={{ display: "none" }}>
                    <Browser
                      store={taskMainTagBrowserStore}
                      isSingle={false}
                      type={"wrltag"}
                      valueArray={[]}
                      onChange={(...arg) => {
                        this.onTagBrowserChange(arg[2])
                      }}
                    />
                  </div>
                </div>
                :
                <WrMenu
                  data={bottomMenuDatas}
                  onSelect={(data) => {
                    // this.updateViewInfo()
                    this.onBottomMenuSelect(data)
                  }}
                  iconType={"plus"}
                  onIconClick={() => { this.onCreateNewTask() }}
                  currentkey={condtype}
                  _width={"130px"}
                />
            }
          </div>

          <Switch>
            <Route name='taskMainAdvancedSearch' breadcrumbName={getLabel(347, '高级搜索')} path={'/taskHome/taskMain/advancedSearch'} render={() => { return this.renderAdvancedSearch() }} />
            <Route name='taskMainSubUser' breadcrumbName={getLabel(17494, "所有下属")} path={'/taskHome/taskMain/subUser'} render={() => { return this.renderSubUser() }} />
            <Route name='taskMainTagManage' breadcrumbName={"标签管理"} path={'/taskHome/taskMain/tagManage'} render={() => { return this.renderTagManage() }} />
          </Switch>
        </div >
        :
        <WrAlertPage show={true} msg={getLabel(509275, "您的系统未开启任务管理模块")} icon={"no-data"} top="35%" />
      )
    )
  }
}

export default TaskMain